package com.xhw.web.interceptor;

import java.lang.reflect.Method;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.xhw.web.annotation.AllowAnonymous;

import wh.coach.web.interceptor.TokenException;

import static com.xhw.web.controller.PersonsController.MANAGER_TOKEN;

/**
 * @Author xhw
 * @Date 2023/8/18
 * @Version 1.0
 */
@Component
public class LoginContextInterceptor implements HandlerInterceptor {

    @Override
    public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
                                final Exception ex) {
    }

    @Override
    public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
                           final ModelAndView modelAndView) {
    }

    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();

            // 检查方法上是否有 @AllowAnonymous 注解
            if (method.isAnnotationPresent(AllowAnonymous.class)) {
                return true; // 允许匿名访问
            }

        }
        //获取请求头
        String token = request.getHeader("Access-Token");

        //对于拿到的token进行判断，匹配就可以继续，不匹配就报错
        if (!Objects.equals(token, MANAGER_TOKEN)) {
            throw new TokenException("token 错误");
        }

        return true;
    }
}
